'use strict';
var async = require('async');
var distUtil = require('../utils/distance.js');
var cache = require('../utils/redis');
var USER_DISTANCE_EXPIRE = require(process.argv[2]).USER_DISTANCE_EXPIRE;
/**
 * [获取位置所在的矩离]回调
 * @param  {[Object]}   from [发出位置]
 * @param  {[Array]}   to   [日的地址可有多个]
 * @param  {Function} cb   [回调]
 * @param  {String} distanceKey   [缓存KEY]
 * @return [type]          [description]
 */
var getDistanceByPostions = function (from, to, userLen, distanceKey, cb) {
  // 计算矩离
  var distanceList = [];
  var distUserId = [];
  to.forEach(function (pos) {
    var distance = distUtil.calDis(from, pos);
    distanceList.push({
      distance: distance,
      userId: pos.userId,
    });
    distUserId.push(pos.userId);
  });
  //  缓存矩离
  if (to.length === userLen) {
    cache.setStrCache(distanceKey, distanceList, USER_DISTANCE_EXPIRE, function () {
      cb({
        distance: distanceList,
        usersId: distUserId
      });

    });
  } else {
    cb({
      distance: distanceList,
      usersId: distUserId
    });
  }

};




exports.getUserPositionStatus = function (userId, callback) {
  var positionKey = 'position_' + userId;
  cache.getStrCache(positionKey, function (err, res) {
    var status = 0;
    if (res) {
      status = 1;
    }
    callback(err, status);
  });
};




/**
 * [获取当前用户相对其它用户的矩离]
 * @param  {[type]}   userId       [当前用户ID]
 * @param  {[type]}   otherUserIds [其它用户IDS]
 * @param  {Function} cb           [description]
 * @return [object]   distance    [用户矩离]
 */

exports.getCurrUserRelativeOtherUsersDistance = function (userId, userIds, _cb) {
  var distanceKey = 'distance_' + userId;
  // 从缓存获取 位置
  var otherUserIds = userIds.slice();
  cache.getStrCache(distanceKey, function (err, distance) {
    if (err) {
      distance = [];
      otherUserIds.forEach(function (_userId) {
        distance.push({
          distance: -1,
          userId: _userId,
        });
      });
      return _cb(distance);
    }
    if (distance) {
      return _cb(distance);
    }
    // 如果获取不到则需要计算
    async.waterfall([
      function (cb) {
        // 从缓存拿到所有用户位置
        otherUserIds.unshift(userId);// 添加当前获取位置用户位置到用户列表。
        async.map(otherUserIds, function (userId, callback) {
          var positionKey = 'position_' + userId;
          cache.getStrCache(positionKey, function (err, res) {
            callback(err, res);
          });
        }, function (err, result) {
          if (err) {
            return cb(err, result);
          }
          var positions = result.filter(function (position) {
            return position !== null;
          });
          cb(null, positions);
        });
      },
      function (result, cb) {
        //  在缓存没有取到用户位置
        var from = {}, to = [];
        result.forEach(function (position) {
          if (position.userId == userId) {
            from = position;
          } else {
            to.push(position);
          }
        });
        if (from.userId && to.length > 0) {
          console.log(from.userId, to.length);
          // 通过用户位置，计算出用户相对矩离
          getDistanceByPostions(from, to, userIds.length, distanceKey, function (distanceList) {
            var distance = distanceList.distance;
            var distUser = distanceList.usersId;
            if (distance.length < userIds.length) {
              userIds.forEach(function (_userId) {
                _userId = parseInt(_userId);
                if (!~distUser.indexOf(_userId)) {
                  distance.push({
                    distance: -1,
                    userId: _userId,
                  });
                }
              });
            }
            cb(null, distance);
          });
        } else {
          var distance = [];
          userIds.forEach(function (_userId) {
            distance.push({
              distance: -1,
              userId: _userId,
            });
          });
          cb(distance);
        }
      }], function (err, result) {
        console.log("error=>", err);
        if (err) {
          return _cb(err);
        }
        _cb(result);
      });
  });
};
